import EventEmitter from "events";
export class RenderView extends EventEmitter {
    textModel_;
    selectionModel_;
    viewContainer_;
    constructor (textModel, selectionModel, viewContainer) {
        super()
        this.textModel_ = textModel
        this.selectionModel_ = selectionModel
        this.viewContainer_ = viewContainer
        this.addEventListener()
    }
    addEventListener () {
        this.textModel_.on('text-change', this.render.bind(this))
        window.document.addEventListener('selectionchange', this.domSelectionChangeHandler.bind(this))
    }
    domSelectionChangeHandler () {
        const domSelection = window.getSelection()
        if (domSelection) {
            this.emit('selection-change', {anchor: domSelection.anchorOffset, focus: domSelection.focusOffset});
        }
    }
    updateDomSelection () {
        const domSelection = window.getSelection()
        if (domSelection) {
            const selectionFromModel = this.selectionModel_.getSelection()
            const anchor = selectionFromModel.anchor
            const range = window.document.createRange()
            range.setStart(this.viewContainer_.childNodes[0], anchor)
            range.setEnd(this.viewContainer_.childNodes[0], anchor)
            domSelection.removeAllRanges()
            domSelection.addRange(range)  
        }
        
    }
    render () {
        this.viewContainer_.innerHTML = this.textModel_.getSpacers() + '\n'
        setTimeout(() => {
            this.updateDomSelection()
        }, 0)
    }
}
export default RenderView